package com.example.safeassistan.hiddendanger.fragment;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.UserInfoModel;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.hiddendanger.activity.HiddendangerUnSubmit;
import com.example.safeassistan.hiddendanger.adapter.HiddenDangerMyAdapter;
import com.example.safeassistan.hiddendanger.adapter.HiddenDangerStatusAdapter;
import com.example.safeassistan.hiddendanger.model.HiddenDangerMyModel;
import com.example.safeassistan.hiddendanger.model.HiddenDangerTotalUser;
import com.example.safeassistan.hiddendanger.model.StatusModel;
import com.example.safeassistan.home.activity.OverDueHiddenDangerDetail;
import com.example.safeassistan.home.activity.RiskPointDetail;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.utile.JsonUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class HiddenDangerMyFragment extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private View view;
    private SmartRefreshLayout refreshLayout;
    private HiddenDangerMyAdapter adapter;
    private List<HiddenDangerMyModel.ResultDTO> data;
    private RecyclerView rcView;
    private LinearLayout llType1,llType2,llType3;
    private TextView tvType1,tvType2,tvType3;
    private TextView tvCommonHiddenDanger,tvBigHiddenDanger,tvTotal;
    private int handletype=0;//状态 0 未处理 1 已处理
    private int level=-1;//等级 1 重大 3 一般
    private int status=-1;// 1待提交 2待评审 3待整改4待验收5已完成6已撤销
    private int currentPage=1;

    private List<StatusModel> ststusHandle;
    private List<StatusModel> ststusUnHandle;

    public static HiddenDangerMyFragment newInstance(int  type) {
        Bundle arguments = new Bundle();
        arguments.putInt("type",type);
        HiddenDangerMyFragment fl = new HiddenDangerMyFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.hiddendanger_my_fragment, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        refreshLayout=view.findViewById(R.id.refresh);
        refreshLayout.finishRefreshWithNoMoreData();
        ststusUnHandle=new ArrayList<>();
        ststusUnHandle.add(new StatusModel("待提交",1));
        ststusUnHandle.add(new StatusModel("待审批",2));
        ststusUnHandle.add(new StatusModel("待整改",3));
        ststusUnHandle.add(new StatusModel("待验收",4));

        ststusHandle=new ArrayList<>();
        ststusHandle.add(new StatusModel("已撤销",6));
        ststusHandle.add(new StatusModel("已提交",7));
        ststusHandle.add(new StatusModel("已评审",8));
        ststusHandle.add(new StatusModel("已整改",9));
        ststusHandle.add(new StatusModel("已验收",5));

        tvCommonHiddenDanger=view.findViewById(R.id.tvCommonHiddenDanger);
        tvBigHiddenDanger=view.findViewById(R.id.tvBigHiddenDanger);
        tvTotal=view.findViewById(R.id.tvTotal);
        llType1=view.findViewById(R.id.llType1);
        llType2=view.findViewById(R.id.llType2);
        llType3=view.findViewById(R.id.llType3);
        rcView=view.findViewById(R.id.rcView);
        tvType1=view.findViewById(R.id.tvType1);
        tvType2=view.findViewById(R.id.tvType2);
        tvType3=view.findViewById(R.id.tvType3);
        llType1.setOnClickListener(this::onClick);
        llType2.setOnClickListener(this::onClick);
        llType3.setOnClickListener(this::onClick);
        data=new ArrayList<>();
        setView();
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible){
            getTopData();
            getData();
        }
    }

    public void setView(){
        data=new ArrayList<>();
        refreshLayout.finishRefreshWithNoMoreData();
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                    }
                }, 1000);
            }
        });
    }


    @Override
    protected void onFragmentFirstVisible() {

    }

    PopupWindow popupWindow=null;
    HiddenDangerStatusAdapter statusAdapter;

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llType1:
                View inflate = LayoutInflater.from(context).inflate(R.layout.popu_hiddendanger_type,null);
                TextView tvUn=inflate.findViewById(R.id.tvUn);
                TextView tvAl=inflate.findViewById(R.id.tvAl);
                tvUn.setWidth(llType1.getWidth());

                tvUn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        handletype=0;
                        tvType1.setText("未处理");
                        tvType1.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });

                tvAl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        handletype=1;
                        tvType1.setText("已处理");
                        tvType1.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.WRAP_CONTENT,
                                  RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llType1,0,-100);
                break;
            case R.id.llType2:
                View inflate1 = LayoutInflater.from(context).inflate(R.layout.popu_hiddendanger_level,null);
                TextView tvBig=inflate1.findViewById(R.id.tvUn);
                TextView tvCommon=inflate1.findViewById(R.id.tvAl);
                TextView tvAll=inflate1.findViewById(R.id.tvAll);
                tvBig.setWidth(llType2.getWidth());

                tvAll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        level=-1;
                        tvType2.setText("等级");
                        tvType2.setTextColor(context.getResources().getColor(R.color.gray3));
                        popupWindow.dismiss();
                        getData();
                    }
                });

                tvBig.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //重大隐患
                        level=3;
                        tvType2.setText("重大隐患");
                        tvType2.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });
                tvCommon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //一般隐患
                        level=1;
                        tvType2.setText("一般隐患");
                        tvType2.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate1, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llType2,0,-100);
                break;
            case R.id.llType3:
                if (handletype==1){
                    //已处理
                     statusAdapter=new HiddenDangerStatusAdapter(ststusHandle);
                }else {
                    //未处理
                     statusAdapter=new HiddenDangerStatusAdapter(ststusUnHandle);
                }
                View inflate2 = LayoutInflater.from(context).inflate(R.layout.popu_hiddendanger_status,null);
                TextView tvTitle=inflate2.findViewById(R.id.tvTitle);
                RecyclerView rcCommon=inflate2.findViewById(R.id.rcCommon);
                rcCommon.setAdapter(statusAdapter);
                rcCommon.setLayoutManager(new LinearLayoutManager(context));
                tvTitle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        status=-1;
                        tvType3.setText("状态");
                        tvType3.setTextColor(context.getResources().getColor(R.color.gray3));
                        popupWindow.dismiss();
                        getData();
                    }
                });
                statusAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        status=statusAdapter.getData().get(position).getId();
                        tvType3.setText(statusAdapter.getData().get(position).getText());
                        tvType3.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });

                tvTitle.setWidth(llType3.getWidth());
                popupWindow = new PopupWindow(inflate2, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llType3,0,-100);
                break;
        }
    }

    public void getData(){
        JSONObject map = new JSONObject();
        try {
            if (level!=-1){
                map.put("level",level);//隐患等级
            }
            if (handletype!=-1){
                map.put("status",handletype);//处理状态
            }
            if (status!=-1){
                map.put("disposeStatus",status);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.queryHiddenDangerByUser, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        refreshLayout.finishRefresh();
                        Object obj = JsonUtils.fromJson(result.toString(), HiddenDangerMyModel.class);
                        if (obj instanceof HiddenDangerMyModel) {
                            HiddenDangerMyModel model=(HiddenDangerMyModel) obj;
                                data.clear();
                                if (model.getResult().size() > 0) {
                                    data=model.getResult();
                                    adapter=new HiddenDangerMyAdapter(data,handletype+"");
                                    rcView.setLayoutManager(new LinearLayoutManager(context));
                                    rcView.setAdapter(adapter);
                                    adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            switch (data.get(position).getDisposeStatus()+""){
                                                case "1":
                                                    //隐患添加页面
                                                    getUserInfo();
                                                    HiddendangerUnSubmit.actionStart(context,model.getResult().get(position).getId(),"",1);
                                                    break;
                                                case "5":
                                                    OverDueHiddenDangerDetail.actionStart(context,
                                                            model.getResult().get(position).getDisposeStatus()+"",
                                                            1,model.getResult().get(position).getId()
                                                            ,model.getResult().get(position).getRectSubmit());
                                                    break;
                                                case "4":
                                                    if (handletype==1){
                                                        OverDueHiddenDangerDetail.actionStart(context,model.getResult().get(position).getDisposeStatus()+"",
                                                                1,model.getResult().get(position).getId()
                                                                ,model.getResult().get(position).getRectSubmit());
                                                    }else {
                                                        OverDueHiddenDangerDetail.actionStart(context,model.getResult().get(position).getDisposeStatus()+"",
                                                                2,model.getResult().get(position).getId()
                                                                ,model.getResult().get(position).getRectSubmit());

                                                    }
                                                    break;
                                                default:
                                                    OverDueHiddenDangerDetail.actionStart(context,model.getResult().get(position).getDisposeStatus()+"",
                                                            2,model.getResult().get(position).getId()
                                                            ,model.getResult().get(position).getRectSubmit());
                                                    break;
                                            }
                                        }
                                    });
                                    rcView.setNestedScrollingEnabled(false);
                                } else {
                                    adapter.notifyDataSetChanged();
                              }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                    refreshLayout.finishRefresh();
            }
        });
    }


    public  void getUserInfo() {
        new HttpRequest(context).doGet(UrlConstants.userInfoqueryPersonage, null,new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), UserInfoModel.class);
                        if (obj instanceof UserInfoModel) {
                            UserInfoModel model = (UserInfoModel) obj;
                            UserData.create(context).saveUserData(model.getResult());
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    public void getTopData(){
        new HttpRequest(context).doPost(UrlConstants.getDefectTotalByUser, null, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), HiddenDangerTotalUser.class);
                        if (obj instanceof HiddenDangerTotalUser) {
                            HiddenDangerTotalUser model=(HiddenDangerTotalUser) obj;
                            tvBigHiddenDanger.setText(model.getResult().get(0).getNum()+"");
                            tvCommonHiddenDanger.setText(model.getResult().get(1).getNum()+"");
                            tvTotal.setText(Integer.parseInt(model.getResult().get(0).getNum())+Integer.parseInt(model.getResult().get(1).getNum())+"");
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }


}